package com.zzyl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JWTConfigProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MemberServiceimpl implements MemberService {
    @Autowired
    private WechatService wechatService;
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private JWTConfigProperties jwtConfigProperties;
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1.调用微信接口获取微信用户的唯一id
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());
        //2.调用微信接口获取用户的电话号码
        String phoneNumber = wechatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        //3.根据微信唯一id去数据库查看之前是否登录过也就是根据openid进行查询
         Member member =  memberMapper.getByopenid(openId);
         //4.判断查询到的返回类型是否为null 如果为null说明之前未登录过做新增操作
        //如果不为null则说明之前登录过要比较现在登录的电话号码和之前数据库存储的电话号码是否相等
        //如果相等则不进行操作 不相等则进行修改操作
        if (ObjectUtil.isNotEmpty(member)) {
            if(!member.getPhone().equals(phoneNumber)) {
                member.setPhone(phoneNumber);
                memberMapper.updatemapper(member);
            }
        }else {
            member = new Member();
            member.setName("花好月圆");
            member.setOpenId(openId);
            member.setPhone(phoneNumber);
            memberMapper.insert(member);
        }
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId",member.getId());
        claims.put("userName",member.getName());
        String token = JwtUtil.createJWT(jwtConfigProperties.getBase64EncodedSecretKey(), jwtConfigProperties.getTtl(), claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());
        return loginVo;
    }
}
